/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.sociesc.findasmartphonespark.utils;

import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;
import com.sociesc.findasmartphonespark.dao.ConnectionFactory;
import com.sociesc.findasmartphonespark.dao.Dao;
import com.sociesc.findasmartphonespark.model.User;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

public class DatabaseUtils {

    public static void createDatabase() throws SQLException {
        ConnectionSource conn = ConnectionFactory.createConn();
        TableUtils.dropTable(conn, User.class, true);
        TableUtils.createTableIfNotExists(conn, User.class);
        conn.close();
    }

    public static String criptPass(String password) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] passBytes = password.getBytes();
            md.reset();
            byte[] digested = md.digest(passBytes);
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < digested.length; i++) {
                sb.append(Integer.toHexString(0xff & digested[i]));
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(DatabaseUtils.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }

    public static void seedDatabase() throws SQLException {
        DatabaseUtils.createDatabase();
        Dao<User> userDao = new Dao(User.class);
        
        for(int i=0;i<10;i++){
            User user = new User();
            user.setName("User_" + i);
            user.setEmail("user_" + i + "@patinhascorp.com");
            String criptPass = criptPass("teste");
            user.setPasswordDigest(criptPass);
            userDao.create(user);
        }

    }

}
